package com.cg.leetcode;

import org.junit.Test;

import java.util.*;

/**
 * 404.左叶子之和
 *
 * @program: LeetCode->LeetCode_404
 * @author: cg
 * @create: 2022-04-24 10:39
 **/
public class LeetCode_404 {

    @Test
    public void test404() {
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);

        root.right = new TreeNode(20);
        root.right.left = new TreeNode(15);
        root.right.right = new TreeNode(7);
        System.out.println(sumOfLeftLeaves(root));
    }

    /**
     * 给定二叉树的根节点 root ，返回所有左叶子之和。
     * <p>
     * 示例 1：
     * 输入: root = [3,9,20,null,null,15,7]
     * 输出: 24
     * 解释: 在这个二叉树中，有两个左叶子，分别是 9 和 15，所以返回 24
     * <p>
     * 示例 2:
     * 输入: root = [1]
     * 输出: 0
     * <p>
     * 提示:
     * 节点数在 [1, 1000] 范围内
     * -1000 <= Node.val <= 1000
     *
     * @param root
     * @return
     */
    public int sumOfLeftLeaves(TreeNode root) {
        // 递归
        if (root == null) {
            return 0;
        }
        int left = sumOfLeftLeaves(root.left);
        int right = sumOfLeftLeaves(root.right);

        int middle = 0;
        if (root.left != null && root.left.left == null && root.left.right == null) {
            middle = root.left.val;
        }
        return left + right + middle;
    }

    /*public int sumOfLeftLeaves(TreeNode root) {
        // 迭代
        if (root == null) {
            return 0;
        }
        Deque<TreeNode> stack = new ArrayDeque<>();
        stack.push(root);
        int res = 0;
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            if (node.left != null && node.left.right == null && node.left.left == null) {
                res += node.val;
            }
            if (node.right != null) {
                stack.push(node.right);
            }
            if (node.left != null) {
                stack.push(node.left);
            }
        }
        return res;
    }*/

    /*public int sumOfLeftLeaves(TreeNode root) {
        // 广度优先搜索
        if (root == null) {
            return 0;
        }
        int res = 0;
        Deque<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    if (node.left.left == null && node.left.right == null) {
                        res += node.left.val;
                    }
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
        }
        return res;
    }*/

}
